var setter;
var $;
var commons;
layui.config({
    base: serverPath.formPath + staticPath.formPath //静态资源所在路径
}).extend({
    // index: 'index' //主入口模块
}).use(['index', 'commons', 'form', 'jquery', 'setter', 'table', 'layer'], function () {
    setter = layui.setter;
    $ = layui.jquery;
    commons = layui.commons;
});

/**
 * 执行查询
 * @param condition 查询条件
 * @param callback 查询完成后的回调
 * @param isSync 是否同步执行。
 */
function DoQuery(condition, callback, isSync) {
    var url = serverPath.formPath + setter.formLinkPath + "formQuery/doQuery";
    var isAsync = true;
    if (isSync != undefined && isSync == true) {
        isAsync = false;
    }
    $.ajax({
        type: "POST",
        url: url,
        async: isAsync,
        data: condition,
        dataType: 'json',
        success: function (data) {
            if (callback) {
                callback(data);
            }
        }
    });
}

/**
 * 通用对话框。
 * @param alias        对话框别名。
 * @param callBack    回调函数。
 * 调用示例：
 * CommonDialog("role",function(data){
 *
 * });
 * data:为json数组或者为json对象。
 * @param paramValueString    向对话框传递的"参数=值"字符串
 * 传入多个则需要使用"&"符号进行连接（user=admin&orgId=1）
 */
function CommonDialog(alias, callBack, paramValueString) {
    if (alias == null || alias == undefined) {
        parent.layer.alert("别名为空！", '提示信息');
        return;
    }
    $.ajax({
        url: serverPath.formPath + setter.formLinkPath + "formDialog/dialogObj",
        dataType: 'json',
        type: "post",
        data: {
            "alias": alias
        },
        success: function (result) {
            var dialogSelectorWin;
            var body;
            if (commons._filterRecord(result)) {
                var obj = result.data;
                var width = obj.width.toString() + "px";
                var name = obj.name;
                var height = obj.height.toString() + "px";
                var displayList = $.trim(obj.displayfield);
                var resultfield = $.trim(obj.resultfield);
                if (displayList == "") {
                    parent.layer.alert("没有设置显示字段！", '提示信息');
                    return;
                }
                if (resultfield == "") {
                    parent.layer.alert("没有设置结果字段！", '提示信息');
                    return;
                }
                var url = serverPath.formPath + setter.formLinkPath + "formDialog/view/show?alias=" + alias + "&dynamicPage=true&isOpenJsonData=false&isOpenShowDialog=true";
                if (paramValueString != '') {
                    url = url + "&" + encodeURI(paramValueString);
                }
                parent.layer.open({
                    type: 2,
                    title: name,
                    shade: 0.3,
                    area: [width, height],
                    btn: ["确定", "取消"],
                    content: url,
                    success: function (layero, index) {
                        dialogSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                        body = parent.layer.getChildFrame('body', index);
                        var selectIds = $("input[name=selectIds]").val();
                        dialogSelectorWin.layui.selList = [];
                        if(selectIds){
                            var idArr = selectIds.split(",");
                            $.each(idArr, function (i, value) {
                                dialogSelectorWin.layui.selList.push({
                                    ID: value
                                });
                            })
                        }
                    },
                    yes: function (index, layero) {
                        dialogSelectorWin.determineQuery();
                        var selectData = body.find("input[name=selectData]").val();
                        var selectDataIds = body.find("input[name=selectDataIds]").val();
                        if (selectData && selectDataIds) {
                            $("input[name=selectIds]").val(selectDataIds);
                            if (callBack) {
                                callBack(selectData,selectDataIds);
                            }
                        }else{
                            if(callBack){
                                callBack(selectData);
                            }
                        }
                        parent.layer.close(index);
                    }
                });
            }
        }
    });
}

/**
 * 组合对话框。
 * @param alias        对话框别名。
 * @param callBack    回调函数。
 * 调用示例：
 * CommonDialog("role",function(data){
 *
 * });
 * data:为json数组或者为json对象。
 * @param paramValueString    向对话框传递的"参数=值"字符串
 * 传入多个则需要使用"&"符号进行连接（user=admin&orgId=1）
 */
function CommonCombinationDialog(alias, callBack, paramValueString) {
    if (alias == null || alias == undefined) {
        parent.layer.alert("别名为空！", '提示信息');
        return;
    }
    $.ajax({
        url: serverPath.formPath + setter.formLinkPath + "formDialog/combinationDialog/edit",
        dataType: 'json',
        type: "post",
        data: {
            "alias": alias
        },
        success: function (result) {
            var dialogSelectorWin;
            var body;
            if (commons._filterRecord(result)) {
                var obj = result.data;
                var width = obj.width.toString() + "px";
                var name = obj.name;
                var height = obj.height.toString() + "px";
                var displayList = $.trim(obj.listDialog.displayfield);
                var resultfield = $.trim(obj.listDialog.resultfield);
                if (displayList == "") {
                    parent.layer.alert("没有设置显示字段！", '提示信息');
                    return;
                }
                if (resultfield == "") {
                    parent.layer.alert("没有设置结果字段！", '提示信息');
                    return;
                }
                var url = serverPath.formPath + setter.formLinkPath + "formDialog/combinationDialog/view/preview?combinationAlias=" + alias + "&isOpenJsonData=false&isOpenShowDialog=true";
                if (paramValueString != '') {
                    url = url + "&" + encodeURI(paramValueString);
                }
                parent.layer.open({
                    type: 2,
                    title: name,
                    shade: 0.3,
                    area: [width, height],
                    content: url,
                    btn: ["确定", "取消"],
                    success: function (layero, index) {
                        dialogSelectorWin = parent.window[layero.find('iframe')[0]['name']];
                        body = parent.layer.getChildFrame('body', index);
                        var selectIds = $("input[name=selectIds]").val();
                        dialogSelectorWin.layui.selList = [];
                        if(selectIds){
                            var idArr = selectIds.split(",");
                            $.each(idArr, function (i, value) {
                                dialogSelectorWin.layui.selList.push({
                                    ID: value
                                });
                            })
                        }
                    },
                    yes: function (index, layero) {
                        dialogSelectorWin.determineQuery();
                        var selectData = body.find("input[name=selectData]").val();
                        var selectDataIds = body.find("input[name=selectDataIds]").val();
                        if (selectData && selectDataIds) {
                            $("input[name=selectIds]").val(selectDataIds);
                            if (callBack) {
                                callBack(selectData,selectDataIds);
                            }
                        }
                        parent.layer.close(index);
                    }
                });
            }
        }
    });
}

//打开自定义对话框
function selectCustomDialog(ele) {
    var target = $(ele).attr('param');
    var dialog = $(ele).attr('dialog');
    var me = $(ele);
    CommonDialog(dialog, function (data,selectIds) {
        var dataObj = JSON.parse(data);
        var str = "";
        if (dataObj instanceof Array) {
            for (var i = 0, d; d = dataObj[i++];) {
                str += d[target] + ",";
            }
            me.prev('input:text').val(str.substring(0, str.length - 1));
        } else {
            me.prev('input:text').val(dataObj[target]);
        }
        me.prev('input:text').prev().val(selectIds);
    });
}

//人员单选选择器
function selectUser(ele) {
    var selectUserName = $(ele).prev();
    var body;
    var userSelectorWin;
    var selectUserNameId = selectUserName.prev();
    parent.layer.open({
        type: 2,
        title: '人员选择器',
        area: ['750px', '700px'],
        btn: ["保存", "取消", "撤销"],
        resize: false,
        content: serverPath.formPath + setter.sysLinkPath + 'dialog/view/singleSysUserDialog?selectUserId=' + selectUserNameId.val(),
        success: function (layero, index) {
            body = parent.layer.getChildFrame('body', index);
            userSelectorWin = parent.window[layero.find('iframe')[0]['name']];
        },
        yes: function (index, layero) {
            userSelectorWin.saveData(index);
            var theUserList = body.find("input[name=selectUser]").val();
            if (theUserList) {
                var item = JSON.parse(theUserList);
                selectUserName.val(item.fullName);
                selectUserNameId.val(item.userId);
            } else {
                selectUserName.val("");
                selectUserNameId.val("");
            }
            parent.layer.close(index);
        },
        btn3: function (index, layero) {
            userSelectorWin.cancelData(index);
            return false //开启该代码可禁止点击该按钮关闭
        }
    });
}

//角色单选选择器
function selectRole(ele) {
    var selectRoleName = $(ele).prev();
    var body;
    var roleSelectorWin;
    var selectRoleNameId = selectRoleName.prev();
    parent.layer.open({
        type: 2,
        title: '角色选择器',
        area: ['750px', '700px'],
        btn: ["保存", "取消", "撤销"],
        resize: false,
        content: serverPath.formPath + setter.sysLinkPath + 'dialog/view/singleSysRoleDialog?selectRoleId=' + selectRoleNameId.val(),
        success: function (layero, index) {
            body = parent.layer.getChildFrame('body', index);
            roleSelectorWin = parent.window[layero.find('iframe')[0]['name']];
        },
        yes: function (index, layero) {
            roleSelectorWin.saveData(index);
            var theRoleList = body.find("input[name=selectRole]").val();
            if (theRoleList) {
                var item = JSON.parse(theRoleList);
                selectRoleName.val(item.roleName);
                selectRoleNameId.val(item.roleId);
            } else {
                selectRoleName.val("");
                selectRoleNameId.val("");
            }
            parent.layer.close(index);
        },
        btn3: function (index, layero) {
            roleSelectorWin.cancelData(index);
            return false //开启该代码可禁止点击该按钮关闭
        }
    });
}

//组织单选选择器
function selectOrg(ele) {
    var selectOrgName = $(ele).prev();
    var body;
    var orgSelectorWin;
    var selectOrgNameId = selectOrgName.prev();
    parent.layer.open({
        type: 2,
        title: '组织选择器',
        area: ['750px', '700px'],
        btn: ["保存", "取消", "撤销"],
        resize: false,
        content: serverPath.formPath + setter.sysLinkPath + 'dialog/view/singleSysOrgDialog?selectOrgId=' + selectOrgNameId.val(),
        success: function (layero, index) {
            body = parent.layer.getChildFrame('body', index);
            orgSelectorWin = parent.window[layero.find('iframe')[0]['name']];
        },
        yes: function (index, layero) {
            orgSelectorWin.saveData(index);
            var theOrgList = body.find("input[name=selectOrg]").val();
            if (theOrgList) {
                var item = JSON.parse(theOrgList);
                selectOrgName.val(item.name);
                selectOrgNameId.val(item.orgId);
            } else {
                selectOrgName.val("");
                selectOrgNameId.val("");
            }
            parent.layer.close(index);
        },
        btn3: function (index, layero) {
            orgSelectorWin.cancelData(index);
            return false //开启该代码可禁止点击该按钮关闭
        }
    });
}